import 'package:erp/data/model/page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

abstract class PageListControl<T> extends GetxController {
  final ScrollController scrollController = ScrollController();
  final EasyRefreshController easyRefreshController = EasyRefreshController();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    scrollController.dispose();
    easyRefreshController.dispose();
  }

  @protected
  final int firstPageIndex;

  @protected
  int pageIndex;

  // 当前列表的数据
  List<T> dataList = [];

  PageListControl({int firstPageIndex = 1})
      : this.firstPageIndex = firstPageIndex,
        this.pageIndex = firstPageIndex;

  Future<PageData<T>> loadPageData({required int pageIndex});

  ///上拉加载
  Future onLoad() async {
    bool noMore = false;
    try {
      var _pageData = (await loadPageData(pageIndex: ++pageIndex)).records;
      if (_pageData.isEmpty) {
        noMore = true;
      }
      dataList.addAll(_pageData);
      easyRefreshController.finishLoad(success: true, noMore: noMore);
      update();
    } catch (e) {
      --pageIndex;
      easyRefreshController.finishLoad(success: false);
      update();
    }
  }

  ///下拉刷新
  Future onRefresh() async {
    try {
      easyRefreshController.resetLoadState();
      easyRefreshController.resetRefreshState();
      reset();
      pageIndex = firstPageIndex;
      var pageData = await loadPageData(pageIndex: firstPageIndex);
      if (pageData.noMoreData) {
        easyRefreshController.finishLoad(success: true, noMore: true);
      }
      dataList = pageData.records;
      easyRefreshController.finishRefresh(success: true);
      update();
    } catch (e) {
      easyRefreshController.finishRefresh(success: false);
      update();
    }
  }

  void reset() {
    dataList = [];
  }
}
